package com.kunkun.subject.application.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Feign请求拦截器
 *
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
//通过Feign客户端发起HTTP请求之前，
// 从当前的Servlet请求中提取loginId头部信息，并将其添加到Feign请求模板中。
// 这样，当Feign客户端发送请求到远程服务时，loginId头部信息就会被包含在内。
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取当前线程绑定的请求属性
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (Objects.nonNull(request)) {
            String loginId = request.getHeader("loginId");
            if (StringUtils.isNotBlank(loginId)) {
                //将获取到的loginId添加到Feign请求模板的头部信息中
                requestTemplate.header("loginId", loginId);
            }
        }
    }

}

